package com.scut.fy.admin.controller;

import com.scut.fy.admin.model.dto.ImageCodeDto;
import com.scut.fy.admin.service.ImageCodeService;
import com.scut.fy.common.core.util.Assert;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码接口
 * @author JY
 */
@RestController
@RequestMapping("/imageCode")
public class ImageCodeController {

    private static final Logger log = LoggerFactory.getLogger(ImageCodeController.class);

    @Autowired
    private ImageCodeService imageCodeService;

    @GetMapping("/create/{randomStr}")
    public void createImageCode(@PathVariable final String randomStr,
                               final HttpServletRequest httpServletRequest,
                               final HttpServletResponse httpServletResponse) {
        Assert.isBlank(randomStr, "随机码不能为空");
        httpServletResponse.setHeader("Cache-Control", "no-store, no-cache");
        httpServletResponse.setContentType("image/jpeg");
        try {
            // 通过随机字符串生成图片验证码.并存入redis
            ImageCodeDto imageCodeDto = imageCodeService.createImageCode(randomStr);
            // 验证码的图片报文返回
            ServletOutputStream out = httpServletResponse.getOutputStream();
            ImageIO.write(imageCodeDto.getCodeImage(), "JPEG", out);
            IOUtils.closeQuietly(out);
        } catch (Exception e) {
            log.error("返回验证码错误", e);
        }
    }
}
